/************************************************************
 * 文件名: hexdump.cpp
 * 作者: 黄振杰（huangzhenjie.hzj.ac.cn）
 * 版权: (c) 黄振杰
 * 日期: 2024-03-03
 * 描述: 该工具用于读取文件并以十六进制格式转储其内容。
 ************************************************************/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <cstdlib>

void usage() {
    std::cout << "Hexdump Tool" << std::endl;
    std::cout << std::endl;
    std::cout << "Description: This tool reads a file and dumps its contents in hexadecimal format." << std::endl;
    std::cout << std::endl;
    std::cout << "Usage: hexdump.exe -i input_file" << std::endl;
    std::cout << std::endl;
    std::cout << "Options:" << std::endl;
    std::cout << " -i, --input     Specify the input file to be dumped." << std::endl;
    std::cout << std::endl;
    std::cout << "Example:" << std::endl;
    std::cout << "  hexdump.exe -i input.txt" << std::endl;
    std::cout << "  hexdump.exe -i input.txt >> hzj.txt" << std::endl;
    std::cout << std::endl;
    exit(EXIT_SUCCESS);
}

int main(int argc, char* argv[]) {
    if (argc < 3) {
        usage();
    }

    if (std::strcmp(argv[1], "-i") != 0 && std::strcmp(argv[1], "--input") != 0) {
        std::cerr << "未提供输入文件选项" << std::endl;
        return EXIT_FAILURE;
    }

    std::ifstream file(argv[2], std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "无法打开文件: " << errno << std::endl;
        return EXIT_FAILURE;
    }

    const int buffer_size = 16;
    char buffer[buffer_size];

    int line_number = 0;
    std::cout << "" << std::endl;
    while (file.read(buffer, buffer_size)) {
        std::cout << std::hex << std::setw(8) << std::setfill('0') << line_number << ": ";
        for (int i = 0; i < buffer_size; ++i) {
            if (buffer[i] > -1) {
                std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(buffer[i]) << " ";
            }
            else
            {
                std::cout << std::hex << std::setw(2) << std::setfill('0') << 0 << " ";
            }
          
        }
        std::cout << " ";
        for (int i = 0; i < buffer_size; ++i) {
            char c = buffer[i];
            if (c >= 32 && c <= 126) {
                std::cout << c;
            }
            else {
                std::cout << ".";
            }
        }
        std::cout << std::endl;
        line_number += buffer_size;
    }

    if (file.eof()) {
        // 读取文件结束
        std::cout << "文件已结束" << std::endl;
    }
    else if (file.bad()) {
        // 发生严重错误
        std::cerr << "发生严重错误" << std::endl;
    }
    else if (file.fail()) {
        // 读取失败
        std::cerr << "读取失败" << std::endl;
    }
 
    file.close();

    
    return EXIT_SUCCESS;
}
